package com.my.vote.pst.main;

import com.my.vote.entity.EVoteInfo;
import com.my.vote.entity.req.ReqVoteList;
import com.sfh.lib.AppCacheManager;
import com.sfh.lib.mvp.service.AbstractPresenter;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobObject;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * 功能描述:
 *
 * @author
 * @date 2018/4/12
 */
public class PstMain extends AbstractPresenter<IPstMain.IVMain> implements IPstMain {


    @Override
    public void listPage(final ReqVoteList req) {
        BmobQuery<EVoteInfo> query = new BmobQuery<>();
        // 限制最多10条数据结果作为一页
        query.setLimit(10);
        // 忽略前10条数据（即第一页数据结果）
        query.setSkip(10 * req.getNowPage());
        // 根据score字段降序显示数据
        query.order("-createdAt");
        query.findObjects(AppCacheManager.getApplication(), new FindListener<EVoteInfo>() {
            @Override
            public void onSuccess(List<EVoteInfo> list) {
                if (!list.isEmpty()) {

                    getView().onPageList(req.getNowPage(), list.size() >= 10 ? req.getNowPage() + 1 : req.getNowPage(), list);

                    List<BmobObject> objects = new ArrayList<>(list.size());
                    for (EVoteInfo info : list) {
                        int visitSize = info.getVisitSize() + 1;
                        info.setVisitSize(visitSize);
                        objects.add(info);
                    }
                    new BmobObject().updateBatch(AppCacheManager.getApplication(), objects, new UpdateListener() {
                        @Override
                        public void onSuccess() {

                        }

                        @Override
                        public void onFailure(int i, String s) {

                        }
                    });

                } else {
                    getView().onPageError("No Data!");
                }
            }

            @Override
            public void onError(int i, String s) {
                getView().onPageError("No Data!");
            }
        });

    }


}
